package auth

import (
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"monoblog/util"
	"time"
)

func GenerateJWT(user *LoginUser, secretKey string) (string, error) {
	claims := &JWTClaims{
		UID:    user.UID,
		Name:   user.Name,
		Avatar: user.Avatar,
		Roles:  user.Roles,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
			Issuer:    "monoblog",
			ID:        util.Uuid(),
		},
	}
	// 使用HS256签名算法
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(secretKey))
}

func ParseJWT(tokenString string, secretKey string) (*LoginUser, error) {
	token, err := jwt.ParseWithClaims(tokenString, &JWTClaims{}, func(t *jwt.Token) (any, error) {
		return []byte(secretKey), nil
	})
	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*JWTClaims); ok && token.Valid {
		//转换为LoginUser
		loginUser := &LoginUser{
			UID:    claims.UID,
			Name:   claims.Name,
			Avatar: claims.Avatar,
			Roles:  claims.Roles,
		}
		return loginUser, nil
	}
	return nil, fmt.Errorf("invalid token claims")
}
